package com.easy.security.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.easy.common.core.domain.dto.UserDTO;
import com.easy.common.core.domain.dto.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.easy.common.utils.RedisConstants.*;

/**
 * 刷新 令牌 拦截器
 *
 * @author RuoYu
 * @date 2022/11/22
 */
@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /*
    未携带token传入：返回token为空，权限不足；
    错误token传入：返回token错误，权限不足；
    正常token传入：通过 。
    正常token但已过期：查询redis中该token是否存在，如果缓存中存在则刷新token，并将刷新后的token重新放入redis，使用刷新后的token请求资源； 缓存中不存在，则token刷新期限已过，用户需重新登录。
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头中的token
        String token = request.getHeader("authorization");

        //为空
        if (StrUtil.isBlank(token)) {
            return true;
        }

        // 2.基于TOKEN获取redis中的用户
        String key = LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        log.info("userMap:{}", userMap);
        // 3.判断用户是否存在
        if (userMap.isEmpty()) {
            return true;
        }

        // 5.将查询到的hash数据转为UserDTO
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        log.info("userDTO:{}", userDTO);
        // 6.存在，保存用户信息到 ThreadLocal
        UserHolder.saveUser(userDTO);

        long id = Thread.currentThread().getId();
        log.info("token1：{}", id);
        // 7.刷新token有效期
        Long time = stringRedisTemplate.getExpire(key, TimeUnit.MINUTES);
        if (time < LOGIN_SURPLUS_TTL) {
            stringRedisTemplate.expire(key, LOGIN_USER_TTL, TimeUnit.MINUTES);
        }

        // 8.放行
        return true;
    }

    @Autowired
    private RestHighLevelClient client;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        client.close();

        // 移除用户
        UserHolder.removeUser();
        long id = Thread.currentThread().getId();
        log.info("token2：{}", id);
    }
}
